package com.access.boot.apisdk.param.resolve.argument;

import com.access.boot.apisdk.RequestContext;
import com.access.boot.apisdk.annotation.Path;
import com.access.boot.apisdk.annotation.ValueConstants;
import com.access.boot.apisdk.exception.MethodArgumentEmptyException;
import com.access.boot.apisdk.param.resolve.AbstractNamedValueMethodArgumentResolver;
import com.access.boot.apisdk.util.MethodParameter;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * @author YangZhen
 * @date 2022/6/18 15:59
 * @since 1.0.0
 */
public class PathVariableMethodArgumentResolver extends AbstractNamedValueMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        if (!parameter.hasParameterAnnotation(Path.class)) {
            return false;
        }
        return true;
    }

    @Override
    protected void resolveNamedValue(RequestContext httpRequest, String name, MethodParameter parameter, Object[] arguments) {
        Object argument = arguments[parameter.getParameterIndex()];
        if (argument == null) {
            throw new MethodArgumentEmptyException("Path argument of named [" + name + "] can't be empty.");
        }
        List<String> pathSegments = httpRequest.getPathSegments();
        for (int i = 0; i < pathSegments.size(); i++) {
            String path = pathSegments.get(i);
            path = StringUtils.trim(path);
            if (("{" + name + "}").equals(path)) {
                httpRequest.setPathValue(i, argument.toString());
            }
        }
    }

    @Override
    protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
        Path ann = parameter.getParameterAnnotation(Path.class);
        return new PathVariableNamedValueInfo(ann);
    }

    private static class PathVariableNamedValueInfo extends NamedValueInfo {
        public PathVariableNamedValueInfo(Path annotation) {
            super(annotation.name(), annotation.value(), annotation.required(), ValueConstants.DEFAULT_NONE);
        }
    }

}
